<?php

namespace app\api\controller;

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;

class Index extends Base
{
    public $accessKeyId = "LTAI4G5dGuDFgvzjm8wSqReQ";
    public $accessKeySecret = "JSyjc0KA3o1aesHivcuDUZoQicXJJe";
    private $areasShengShi = [
        '上海市'
    ];

    public function __construct()
    {
        parent::__construct();
    }

    public function checkServerOld()
    {
        if (request()->isPost()) {
            $host = request()->host();
//            $host = 'bini.xdhej.xyz';
            if ($host == "www.xdhej.xyz") {//人人影迷
                // $data =  ['code'=>1,'msg'=>'server\'s online!'];
                // $this->success($data['msg'],null,$data);
            }
            if ($host == "bini.xdhej.xyz") {//比尼影视
//                $this->checkServerIp();
//                return ;
//                $data =  ['code'=>1,'msg'=>'server\'s online!'];
//                $this->success($data['msg'],null,$data);
            }
            if ($host == "www.biniok.xyz") {//比尼影视
//                $this->checkServerIp();
//                return ;
//                $data =  ['code'=>1,'msg'=>'server\'s online!'];
//                $this->success($data['msg'],null,$data);
            }
            if ($host == "woaijutou.xdhej.xyz") {//我爱剧透
                $data = ['code' => 1, 'msg' => 'server\'s online!'];
                $this->success($data['msg'], null, $data);
            }
            // if($host =="www.bucuo.online"){//千文影视
            //     $data =  ['code'=>1,'msg'=>'server\'s online!'];
            //     $this->success($data['msg'],null,$data);
            // }
            $ip = get_client_ip(0, true);
            $ipLast = get_client_ip();
            if (strpos($ip, '17.') === 0 || strpos($ip, '98.') === 0 || strpos($ipLast, '98.') === 0 || strpos($ipLast, '17.') === 0 || strpos($ip, '144.178.') === 0 || strpos($ipLast, '144.178.') === 0 || strpos($ip, '98.207.') === 0 || strpos($ipLast, '98.207.') === 0 || strpos($ip, '73.') === 0 || strpos($ipLast, '73.') === 0
                // || strpos($ip, '60.210.') === 0 || strpos($ipLast, '60.210.') === 0
            ) {
                $data = ['code' => 1, 'msg' => 'server\'s online!'];
            } else {
                //code=1 原app code=3333 影视app
                // $data = ['coxde'=>1,'msg'=>'server\'s online!'];
                $data = ['code' => 3333, 'msg' => 'server\'s online!'];
            }

            $this->success($data['msg'], null, $data);
        } else {
            $this->success('error request!!!');
        }
    }

    public function checkServer()
    {
        if (request()->isPost()) {
            $host = request()->host();
            if ($host == "woaijutou.xdhej.xyz") {//我爱剧透
                $data = ['code' => 1, 'msg' => 'server\'s online!'];
                $this->success($data['msg'], null, $data);
            }
//            if ($host == "www.dtfilm.xyz") {//饭桌影视
//                $data = ['code' => 1, 'msg' => 'server\'s online!'];
//                $this->success($data['msg'], null, $data);
//            }
            if ($host == "www.dtvok.xyz") {//南孙影视
                $data = ['code' => 1, 'msg' => 'server\'s online!'];
                $this->success($data['msg'], null, $data);
            }
            if ($host == "www.nsok.site") {//南孙影视
                $data = ['code' => 1, 'msg' => 'server\'s online!'];
                $this->success($data['msg'], null, $data);
            }
            $data = ['code' => 1, 'msg' => 'server\'s online!'];
            $ip = get_client_ip(0, true);
//            $ip = '17.57.26.123';//apple
//            $ip = '99.240.128.168';//加拿大
//            $ip ='119.82.24.93';//  日本
//            $ip = '101.87.84.46';//上海市
//            $ip = '111.204.125.34';//北京市
//            $ip ='153.99.252.180';//江苏省
            $appId = input('app_id');
            $deviceId = input('device_id');
            if (empty($appId)) {
                $appId = input('appId');
            }
            if (empty($deviceId)) {
                $deviceId = input('deviceId');
            }
            // $checkIpRegionResult -1 表示需要重新获取IP信息 1 表示可以跳转  0 表示不能跳转
            $checkIpRegionResult = $this->checkIpRegion($ip, $appId, $deviceId);
//            dump($checkIpRegionResult.'  === ');
            if ($checkIpRegionResult === -1) {
                $checkIpRegionResult = $this->checkIpRegion($ip, $appId, $deviceId);

            }
//            dump($checkIpRegionResult.'  === ');

            if ($checkIpRegionResult === 1) {
                $data['code'] = 3333; //3333表示允许
            }

            $this->success($data['msg'], null, $data);
        } else {
            $this->success('error request!!!');
        }
    }
    public function checkArea()
    {
        if (request()->isPost()) {
            $host = request()->host();
            if ($host == "woaijutou.xdhej.xyz") {//我爱剧透
                $data = ['code' => 1, 'msg' => 'server\'s online!'];
                $this->success($data['msg'], null, $data);
            }
            $data = ['code' => 1, 'msg' => 'server\'s online!'];
            $ip = get_client_ip(0, true);
//            $ip = '17.57.26.123';//apple
//            $ip = '99.240.128.168';//加拿大
//            $ip ='119.82.24.93';//  日本
//            $ip = '101.87.84.46';//上海市
//            $ip = '111.204.125.34';//北京市
//            $ip ='153.99.252.180';//江苏省
            $appId = input('app_id');
            $deviceId = input('device_id');
            if (empty($appId)) {
                $appId = input('appId');
            }
            if (empty($deviceId)) {
                $deviceId = input('deviceId');
            }
            // $checkIpRegionResult -1 表示需要重新获取IP信息 1 表示可以跳转  0 表示不能跳转
            $checkIpRegionResult = $this->checkIpRegion($ip, $appId, $deviceId);
//            dump($checkIpRegionResult.'  === ');
            if ($checkIpRegionResult === -1) {
                $checkIpRegionResult = $this->checkIpRegion($ip, $appId, $deviceId);

            }
//            dump($checkIpRegionResult.'  === ');

            if ($checkIpRegionResult === 1) {
                $data['code'] = 3333;
            }

            $this->success($data['msg'], null, $data);
        } else {
            $this->success('error request!!!');
        }
    }
    public function savourhotel()
    {
        if (request()->isPost()) {
            $host = request()->host();
            $data = ['status' => 'ok', 'msg' => 'server\'s online!'];
            //$this->success($data['msg'], null, $data);
            $ip = get_client_ip(0, true);
//            $ip = '17.57.26.123';//apple
//            $ip = '99.240.128.168';//加拿大
//            $ip ='119.82.24.93';//  日本
//            $ip = '101.87.84.46';//上海市
//            $ip = '111.204.125.34';//北京市
//            $ip ='153.99.252.180';//江苏省
            $appId = input('app_id');
            $deviceId = input('device_id');
            if (empty($appId)) {
                $appId = input('appId');
            }
            if (empty($deviceId)) {
                $deviceId = input('deviceId');
            }
            // $checkIpRegionResult -1 表示需要重新获取IP信息 1 表示可以跳转  0 表示不能跳转
            $checkIpRegionResult = $this->checkIpRegion($ip, $appId, $deviceId);
//            dump($checkIpRegionResult.'  === ');
            if ($checkIpRegionResult === -1) {
                $checkIpRegionResult = $this->checkIpRegion($ip, $appId, $deviceId);

            }
//            dump($checkIpRegionResult.'  === ');

            if ($checkIpRegionResult === 1) {
                $data['status'] = 'ready'; //ready表示允许
            }

            $this->success($data['msg'], null, $data);
        } else {
            $this->success('error request!!!');
        }
    }
    public function freshseawarehouse()
    {
        if (request()->isPost()) {
            $host = request()->host();
            $data = ['status' => 'ok', 'msg' => 'server\'s online!'];
            //$this->success($data['msg'], null, $data);
            $ip = get_client_ip(0, true);
//            $ip = '17.57.26.123';//apple
//            $ip = '99.240.128.168';//加拿大
//            $ip ='119.82.24.93';//  日本
//            $ip = '101.87.84.46';//上海市
//            $ip = '111.204.125.34';//北京市
//            $ip ='153.99.252.180';//江苏省
            $appId = input('app_id');
            $deviceId = input('device_id');
            if (empty($appId)) {
                $appId = input('appId');
            }
            if (empty($deviceId)) {
                $deviceId = input('deviceId');
            }
            // $checkIpRegionResult -1 表示需要重新获取IP信息 1 表示可以跳转  0 表示不能跳转
            $checkIpRegionResult = $this->checkIpRegion($ip, $appId, $deviceId);
//            dump($checkIpRegionResult.'  === ');
            if ($checkIpRegionResult === -1) {
                $checkIpRegionResult = $this->checkIpRegion($ip, $appId, $deviceId);

            }
//            dump($checkIpRegionResult.'  === ');

            if ($checkIpRegionResult === 1) {
                $data['status'] = 'ready'; //ready表示允许
            }

            $this->success($data['msg'], null, $data);
        } else {
            $this->success('error request!!!');
        }
    }

    /**
     * @param $ip
     * @param $appId
     * @param $deviceId
     * @return int   -1表示需要重新获取IP 1 表示跳转  0 表示不跳转
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    protected function checkIpRegion($ip, $appId, $deviceId)
    {
        //检查设备表是否存在 不存在则写入设备表
        $deviceModel = db('device');
        if (!empty($appId)) {
            $deviceModel = $deviceModel->where('app_id', $appId);
        }
        $deviceInfo = $deviceModel->where('device_id', $deviceId)->find();
        if (!empty($deviceInfo)) {
//
//            //如果设置了可以跳转直接返回1
//            switch ($deviceInfo['can_jump']) {
//                case 1: //1 表示开启跳转
//                    return 1;
//                    break;
//                case -1: //-1表示不跳转
//                    return 0;
//                    break;
//                case 0: //表示需要检查ip情况
//                default:
//                    break;
//            }
            if(empty($appId)){
                $appId = $deviceInfo['app_id'];
            }
            $isExistDevice = true;
        } else {
            $isExistDevice = false;
            $deviceInfo = [
                'first_ip' => '',
                'ip' => ''
            ];
        }
//        dump('deviceInfo');
//        dump(db('device')->getLastSql());
//        dump($deviceInfo);
        $appInfo = db('banben')->where('app_id',$appId)->find();
        if(!empty($appInfo)){
            $disabledAreas= explode(',',$appInfo['heimingdan_jumpshengshi']);
            $this->areasShengShi = array_merge($this->areasShengShi,$disabledAreas);
        }else{
            $disabledAreas = getDisableAreasByAppId($appId);
            if($disabledAreas!==false){
                $this->areasShengShi = $disabledAreas;
            }
        }


//        dump($this->areasShengShi);

        if (empty($deviceInfo['first_ip'])) {
            $firstLog = db('state')->where('device_id', $deviceId)->order('time_added', 'asc')->field('ip')->find();
//            dump(db('state')->getLastSql());
//            dump($firstLog);
            if (!empty($firstLog)) {
                //有观影记录第一次ip记录使用第一次访问的IP记录
                $firstIp = $firstLog['ip'];
            } elseif (!empty($deviceInfo['ip'])) {
                //没有观影记录 且不是新用户，第一次的IP使用 设备表的IP
                $firstIp = $deviceInfo['ip'];
            } else {
                //没有过观影记录那么 就是当前IP
                $firstIp = $ip;
            }
            if($isExistDevice)
                $deviceModel->where('device_id', $deviceId)->where('can_jump', 0)->update([
                    'first_ip' => $firstIp
                ]);
            $deviceInfo['first_ip'] = $firstIp;
        }
//        dump($deviceInfo);exit;
//        dump($deviceInfo['can_jump'].'    c an jum p');
        $ipInfo = db('ip')->where('ip', $deviceInfo['first_ip'])->find();
        if (empty($ipInfo)) {
            $ipInfo = $this->getIpInfo($deviceInfo['first_ip']);
            if ($ipInfo === false) {
                return 0;
            }
        }
//        dump($ipInfo);
        if (empty($ipInfo) || empty($ipInfo['guo_code'])) {
            return -1;
        }
        if (strtolower($ipInfo['guo_code']) != 'cn') {
//            if ($isExistDevice)
//                $deviceModel->where('device_id', $deviceId)->where('can_jump', 0)->update([
//                    'can_jump' => -1
//                ]);
            return 0;
        }

        if (in_array($ipInfo['sheng'], $this->areasShengShi)) {
//            if ($isExistDevice)
//                $deviceModel->where('device_id', $deviceId)->where('can_jump', 0)->update([
//                    'can_jump' => -1
//                ]);
            return 0;
        }else if (!empty(trim($ipInfo['shi'])) && in_array($ipInfo['shi'], $this->areasShengShi)) {
//            if ($isExistDevice)
//                $deviceModel->where('device_id', $deviceId)->where('can_jump', 0)->update([
//                    'can_jump' => -1
//                ]);
            return 0;
        }
//        if ($isExistDevice)
//            $deviceModel->where('device_id', $deviceId)->where('can_jump', 0)->update([
//                'can_jump' => 1
//            ]);
        return 1;
    }

    public function index()
    {
    }

    public function m3u8test()
    {
        exit;
        $page = input('page');
        if (empty($page)) {
            $page = 1;
        }
        $limit = ($page - 1) * 60;
        $nom3u8 = [];
        $data = \db('vod')->limit($limit, 60)->order("vod_id asc")->field("vod_id,vod_pic,vod_name,vod_play_url,vod_status")->select();
        if (!empty($data)) {
            foreach ($data as $k => &$v) {
                $vod_play_url = explode("$$$", $v['vod_play_url']);
                $vod_play_url2 = explode("$", $vod_play_url[0]);
                if (!strstr($vod_play_url2[1], '.m3u8')) {
                    $nom3u8[] = $v;
                }
                $v['vod_play_url'] = $vod_play_url2[1];
            }
        }
        dump($page);
        dump($page);
        dump($nom3u8);
        if (!empty($nom3u8)) {
            exit;
        }
        header("refresh:1;url=http://video.acorntimes.com/api.php/index/m3u8test?page=" . ($page + 1));
        exit;
        $this->success('', '', $data);
    }

    public function getIpInfo($ip)
    {
        AlibabaCloud::accessKeyClient($this->accessKeyId, $this->accessKeySecret)
            ->regionId('cn-hangzhou')
            ->asDefaultClient();
        try {
            $result = AlibabaCloud::rpc()
                ->product('geoip')
                // ->scheme('https') // https | http
                ->version('2020-01-01')
                ->action('DescribeIpv4Location')
                ->method('POST')
                ->host('geoip.aliyuncs.com')
                ->options([
                    'query' => [
                        'Ip' => $ip,
                    ],
                ])
                ->request();
            $resultArray = $result->toArray();

            $ipInfo = [
                'ip' => $ip,
                'x' => $resultArray['Longitude'],
                'y' => $resultArray['Latitude'],
                'sheng' => $resultArray['Province'],
                'shi' => $resultArray['City'],
                'guo' => $resultArray['Country'],
                'guo_code' => $resultArray['Country']=='局域网'?'other':$resultArray['CountryCode'],
                'from'=>'api/index/checkserver'
            ];
            //新增
            try {
                db('ip')->insert($ipInfo);
//                        dump('=====' . db('ip')->getLastSql());
            } catch (\Exception $e) {
                db('ip')->where('ip', $ip)->update($ipInfo);
//                        dump('A ===' . db('ip')->getLastSql());

            }
            return $ipInfo;
//                    dump($ipInfo);
        } catch (ClientException $e) {
            return false;
//                echo $e->getErrorMessage() . PHP_EOL;
        } catch (ServerException $e) {
//                echo $e->getErrorMessage() . PHP_EOL;
            return false;
        }
    }
}
